package com.kma.summer2012.client.presenters.manager;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.constants.ConstantsHolder;
import com.kma.summer2012.client.events.FillViewMapEvent;
import com.kma.summer2012.client.events.request.MainPageEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.presenters.viewmap.ViewMapPresenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.request.CrumbsRequestService;
import com.kma.summer2012.client.services.session.CrumbsSessionService;
import com.kma.summer2012.client.services.user.CrumbsUserService;
import com.kma.summer2012.client.view.PopUpPreloader;
import com.kma.summer2012.client.view.viewmap.ViewMap;
import com.kma.summer2012.shared.model.UICrumbsDateAndTime;
import com.kma.summer2012.shared.model.UICrumbsRequest;
import com.kma.summer2012.shared.model.UICrumbsUser;
import com.kma.summer2012.shared.model.UICrumbsWorkItem;

import java.util.Date;
import java.util.List;
import java.util.Map;


public class AssignPagePresenter implements Presenter {
    public interface Display {
        public void makeListOfTimeBegin();

        public ListBox getListOfUsers();

        public ListBox getListOfTimeBegin();

        public Button getAssignButton();

        public Button getCancelButton();

        public String getUser();

        public String getAssignTimeBegin();

        public void backButtonVisible(Boolean visible);

        public void setLabelComment(String comment);

        public void setLabelDt(String dt);

        public void setLabelT(String time);

        public void setLabelWork(String work);

        public void changeDateOnCalendar(Date date);

        public ViewMap getViewMap();

        public void setRequest(String text);

        Widget asWidget();
    }

    ViewMapPresenter viewMapPresenter;
    private final Display display;
    int id;
    Date requestedDate;
    int requiredTimeHours;

    public AssignPagePresenter(Display display) {
        this.display = display;

        display.backButtonVisible(false);
        bind();
        CrumbsSessionService.App.getInstance().getParameterInteger("id", new AbstractCallBack<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                AssignPagePresenter.this.display.setRequest("Request №" + integer);
                AssignPagePresenter.this.id = integer;
                setRequestTable(id);
                makeListOfUsers();
                AssignPagePresenter.this.display.makeListOfTimeBegin();

            }
        });


    }

    private void bind() {
        display.getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
            }
        });

        this.display.getAssignButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doAssignRequest();
            }
        });

        display.getListOfUsers().addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent changeEvent) {
                if (display.getListOfUsers().getValue(display.getListOfUsers().getSelectedIndex()).equals("Engineers") || display.getListOfTimeBegin().getValue(display.getListOfTimeBegin().getSelectedIndex()).equals("Assign time"))
                    display.getAssignButton().setEnabled(false);
                else
                    display.getAssignButton().setEnabled(true);

            }
        });

        display.getListOfTimeBegin().addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent changeEvent) {
                if (display.getListOfUsers().getValue(display.getListOfUsers().getSelectedIndex()).equals("Engineers") || display.getListOfTimeBegin().getValue(display.getListOfTimeBegin().getSelectedIndex()).equals("Assign time"))
                    display.getAssignButton().setEnabled(false);
                else
                    display.getAssignButton().setEnabled(true);

            }
        });

    }


    public void doAssignRequest() {
        PopUpPreloader.show();
        String dayMonthYearString = DateTimeFormat.getFormat("yyyy-MM-dd").format(requestedDate);
        int hourBegin = DateTimeFormat.getFormat("HH:mm").parse(display.getAssignTimeBegin()).getHours();

        int toHour = hourBegin + requiredTimeHours;

        String dayMonthYearHourString = dayMonthYearString + " " + hourBegin;
        final Date dayMonthYearHourDate = DateTimeFormat.getFormat("yyyy-MM-dd HH").parse(dayMonthYearHourString);

        String dataEndString = dayMonthYearString + " " + toHour;
        Date dateEnd = DateTimeFormat.getFormat("yyyy-MM-dd HH").parse(dataEndString);

        if (toHour <= 18)
            CrumbsRequestService.App.getInstance().assignRequest(Integer.parseInt(display.getUser().substring(0, display.getUser().indexOf("."))), id, dayMonthYearHourDate, dateEnd, new AbstractCallBack<Boolean>() {
                @Override
                public void onSuccess(Boolean result) {
                    if (result) {
                        AssignPagePresenter.this.viewMapPresenter.getEventBus().fireEvent(new FillViewMapEvent(dayMonthYearHourDate));
                        PopUpPreloader.hide();
                        Window.alert("Request was assigned");
                    } else {
                        PopUpPreloader.hide();
                        Window.alert("Engineer already has request at this time or wrong time bounds! ");
                    }
                }

            });
        else {
            PopUpPreloader.hide();
            Window.alert("Engineer does not work around the clock ! Working day is from 9:00 to 18:00");
        }

    }


    public void setRequestTable(int id) {
        this.id = id;
        CrumbsRequestService.App.getInstance().getById(id, new AbstractCallBack<UICrumbsRequest>() {
           @Override
            public void onSuccess(UICrumbsRequest request) {
                display.setLabelComment(request.getRequestInfo());
                String dateString = "";
                for (UICrumbsDateAndTime datetime : request.getUicrumbsDateAndTimes()) {
                    requestedDate = datetime.getDateBegin();
                    dateString = " From " + DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT()).format(datetime.getDateBegin()) + " to " + DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT()).format(datetime.getDateEnd());
                }
                display.setLabelDt(dateString);
                display.changeDateOnCalendar(requestedDate);
                viewMapPresenter = new ViewMapPresenter(AssignPagePresenter.this.display.getViewMap());
                AssignPagePresenter.this.viewMapPresenter.getEventBus().fireEvent(new FillViewMapEvent(requestedDate));
                String workString = "";
                int requiredTime = 0;
                for (Map.Entry<UICrumbsWorkItem, Short> workMap : request.getUicrumbsWorkItems().entrySet()) {
                    workString += workMap.getKey().getWorkName() + ", ";
                    requiredTime += (workMap.getValue()) * ((workMap.getKey().getRuntime()));
                }
                if (requiredTime % 60 == 0) {
                    requiredTimeHours = requiredTime / 60;
                } else {
                    requiredTimeHours = requiredTime / 60 + 1;
                }
                display.setLabelT(String.valueOf(requiredTime) + " minutes ( " + requiredTimeHours + " working hours )");
                display.setLabelWork(workString);
            }
        });
    }

    public void makeListOfUsers() {
        display.getListOfUsers().addItem("Engineers");
        CrumbsUserService.App.getInstance().getAllEngineers(new AbstractCallBack<List<UICrumbsUser>>() {
            @Override
            public void onSuccess(List<UICrumbsUser> users) {
                for (UICrumbsUser user : users)
                    display.getListOfUsers().addItem(String.valueOf(user.getUserId()) + "." + user.getSurnmNmSecondnm());
            }

        });
    }


    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }
}
